package com.sendinfo.sso;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.util.CookieGenerator;

public abstract class HttpUtil {
	public enum SessionKey {
		LOGINED_USER("logined_user"), EXPLORER_IPAREA("explorer_iparea"), LOGINED_DOMAIN("logined_domain"), LOGINING_REDIRECT("logining_redirect"), LOGINING_CHECK_CODE("logining_checkcode"), LOGINING_ACTIVE("active");

		private String key;

		public String getKey() {
			return this.key;
		}

		private SessionKey(String key) {
			this.key = key;
		}
	}

	public static void put(HttpSession session, SessionKey key, Object value) {
		session.setAttribute(key.getKey(), value);
	}

	public static Object get(HttpSession session, SessionKey key) {
		return session.getAttribute(key.getKey());
	}

	public static void remove(HttpSession session, SessionKey key) {
		session.removeAttribute(key.getKey());
	}

	public static void clear(HttpSession session) {
		session.invalidate();
	}

	// Cookie op.
	public static String get(HttpServletRequest req, SessionKey key) {
		Cookie[] cookies = req.getCookies();
		if (null == cookies) return null;
		for (Cookie c : cookies)
			if (c.getName().equals(key.getKey())) return c.getValue();
		return null;
	}

	public static void put(HttpServletResponse resp, SessionKey[] keys, String[] values) {
		CookieGenerator g = new CookieGenerator();
		g.setCookiePath("/");
		g.setCookieMaxAge(86400);//一天时间
		for (int i = 0; i < keys.length; i++) {
			g.setCookieName(keys[i].getKey());
			g.addCookie(resp, values[i]);
		}
	}

	public static void put(HttpServletResponse resp, String[] domains, SessionKey[] keys, String[] values) {
		CookieGenerator g = new CookieGenerator();
		g.setCookiePath("/");
		g.setCookieMaxAge(86400);//一天时间
		for (String domain : domains) {
			g.setCookieDomain(domain);
			for (int i = 0; i < keys.length; i++) {
				g.setCookieName(keys[i].getKey());
				g.addCookie(resp, values[i]);
			}
		}
	}
	
	public static void remove(HttpServletResponse resp, SessionKey[] keys) {
		CookieGenerator g = new CookieGenerator();
		g.setCookiePath("/");

		g.setCookieName(SessionKey.LOGINING_ACTIVE.getKey());
		g.addCookie(resp, "1");
		/*
		for (SessionKey key : keys) {
			g.setCookieName(key.getKey());
			g.removeCookie(resp);
		}
		*/
	}

	public static void remove(HttpServletResponse resp, String[] domains, SessionKey[] keys) {
		CookieGenerator g = new CookieGenerator();
		g.setCookiePath("/");
		for (String domain : domains) {
			g.setCookieDomain(domain);
			for (SessionKey key : keys) {
				g.setCookieName(key.getKey());
				g.removeCookie(resp);
			}
		}
	}

}
